package cn.xlbweb.cli.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.xlbweb.cli.model.Permission;
import cn.xlbweb.cli.pojo.vo.PermissionVO;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

/**
 * @author: bobi
 * @date: 2018/11/18 20:53
 * @description: 系统工具类
 */
public class CliUtils {

    /**
     * 复制非空属性
     *
     * @param source
     * @param target
     */
    public static void copyProperties(Object source, Object target) {
        BeanUtil.copyProperties(source, target, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
    }

    /**
     * List转换为Set
     *
     * @param list
     * @return
     */
    public static Set<String> listToSet(List<String> list) {
        Set<String> set = new HashSet<>();
        for (String str : list) {
            if (StringUtils.isBlank(str)) {
                continue;
            }
            set.addAll(Arrays.asList(str.trim().split(",")));
        }
        return set;
    }

    /**
     * 获取本机IP地址
     *
     * @return
     */
    public static String getLocalIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "127.0.0.1";
    }

    /**
     * 获取批量操作的id集合
     *
     * @param ids
     * @return
     */
    public static List<Integer> getIdList(String ids) {
        String[] array = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            idList.add(Integer.valueOf(array[i]));
        }
        return idList;
    }

    /**
     * 递归获取权限树
     *
     * @param permissionList
     * @param parentId
     * @return
     */
    public static List<PermissionVO> getPermissionTree(List<Permission> permissionList, Integer parentId) {
        List<PermissionVO> permissionVOList = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (permission.getParentId().equals(parentId)) {
                PermissionVO permissionVo = new PermissionVO();
                CliUtils.copyProperties(permission, permissionVo);
                permissionVOList.add(permissionVo);
            }
        }
        for (PermissionVO permissionVo : permissionVOList) {
            permissionVo.setChildren(getPermissionTree(permissionList, permissionVo.getId()));
        }
        return permissionVOList;
    }
}
